import { Modal, Spin, Skeleton } from 'antd';
import React, { FC, useCallback, useEffect, useState } from 'react';

import { createAsyncFormActions } from '@formily/antd';

import { SubmitDialogProps } from '../interface';

import { SchemaFormRender } from '@/components/schema-form-render/index';

import { xhrPostJson } from '@/services';
import { useGetPageMeta } from '../hooks';

import { triggerConvertSubmitParams, triggerConvertDetailValuesType } from '../triggerPlugin';

const actions = createAsyncFormActions();

const SubmitDialog: FC<SubmitDialogProps> = ({
  visible,
  success,
  onCancel,
  title,
  formCode,
  convertSubmitParamsType,
  convertDetailValuesType,
  fetchDetailParams,
  extraSubmitParams,
  saveUrl,
  detailUrl,
}) => {
  const { jsonSchema, loading: initLoading } = useGetPageMeta(formCode);

  const [loading, setLoading] = useState<boolean>(false);
  const [initValues, setInitValues] = useState({});

  const handleOk = () => {
    actions.submit().then(formValues => {
      const { values } = formValues;
      const params = {
        ...values,
        ...extraSubmitParams,
        pageCode: formCode,
      };
      const submitParams = triggerConvertSubmitParams(convertSubmitParamsType, params);
      setLoading(true);
      xhrPostJson(saveUrl, submitParams)
        .then(() => {
          onCancel?.();
          success?.();
        })
        .finally(() => {
          setLoading(false);
        });
    });
  };

  const fetchDetail = useCallback(() => {
    setLoading(true);
    xhrPostJson(detailUrl, fetchDetailParams)
      .then(res => {
        setInitValues(triggerConvertDetailValuesType(convertDetailValuesType, res));
      })
      .finally(() => {
        setLoading(false);
      });
  }, [detailUrl, fetchDetailParams, convertDetailValuesType]);

  useEffect(() => {
    if (visible) {
      fetchDetail();
    }
  }, [visible, fetchDetail]);

  return (
    <Modal
      title={title}
      visible={visible}
      onCancel={onCancel}
      onOk={handleOk}
      width={1080}
      closable={false}
      maskClosable={false}
      bodyStyle={{
        overflowY: 'auto',
      }}
      okText="保存"
    >
      <Skeleton active loading={initLoading}>
        <Spin spinning={loading} tip="搜索中。。。。">
          <SchemaFormRender
            value={initValues}
            actions={actions}
            needGroup={false}
            columns={jsonSchema}
          />
        </Spin>
      </Skeleton>
    </Modal>
  );
};

export default SubmitDialog;
